package com.beauty.user.controller;

import com.beauty.user.dto.LoginRequest;
import com.beauty.user.dto.LoginResponse;
import com.beauty.user.dto.UserResponse;
import com.beauty.user.entity.User;
import com.beauty.user.result.Result;
import com.beauty.user.service.UserService;
import jakarta.persistence.EntityNotFoundException;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/user")
@RequiredArgsConstructor
@Slf4j
public class UserController {

    private final UserService userService;

    @PostMapping("/login")
    public Result<LoginResponse> login(@Valid @RequestBody LoginRequest request) {
        log.info("【用户服务】接收到登录请求，用户名: {}, 是否商家登录: {}", 
                request.getUsername(), request.getIsMerchantLogin());
        return Result.success(userService.login(request));
    }
    
    // 商家登录专用端点
    @PostMapping("/merchant/login")
    public Result<LoginResponse> merchantLogin(@Valid @RequestBody LoginRequest request) {
        log.info("【用户服务】接收到商家登录请求，用户名: {}", request.getUsername());
        // 设置为商家登录
        request.setIsMerchantLogin(true);
        try {
            LoginResponse response = userService.login(request);
            if (Boolean.TRUE.equals(response.getIsMerchant())) {
                log.info("【用户服务】商家登录成功，商家ID: {}", response.getMerchantId());
                return Result.success(response);
            } else {
                log.warn("【用户服务】非商家账号尝试商家登录，用户名: {}", request.getUsername());
                return Result.failed("非商家账号，无法进行商家登录");
            }
        } catch (Exception e) {
            log.error("【用户服务】商家登录失败，用户名: {}", request.getUsername(), e);
            return Result.failed(e.getMessage());
        }
    }

    @PostMapping("/register")
    public Result<User> register(@Valid @RequestBody User user) {
        return Result.success(userService.register(user));
    }
    
    // 商家注册专用端点
    @PostMapping("/merchant/register")
    public Result<User> registerMerchant(@Valid @RequestBody User user) {
        log.info("【用户服务】接收到商家注册请求，用户名: {}", user.getUsername());
        // 设置为商家账号
        user.setIsMerchant(true);
        // 如果未提供商家ID，生成一个
        if (user.getMerchantId() == null || user.getMerchantId().isEmpty()) {
            user.setMerchantId("MER" + System.currentTimeMillis());
        }
        try {
            User registered = userService.register(user);
            log.info("【用户服务】商家注册成功，商家ID: {}", registered.getMerchantId());
            return Result.success(registered);
        } catch (Exception e) {
            log.error("【用户服务】商家注册失败，用户名: {}", user.getUsername(), e);
            return Result.failed(e.getMessage());
        }
    }
    
    @GetMapping("/{userId}")
    public Result<UserResponse> getUserById(@PathVariable String userId) {
        log.info("【用户服务】接收到查询用户请求，用户ID: {}", userId);
        try {
            User user;
            // 判断是否是数字ID或客户ID格式
            if (userId.startsWith("CUS")) {
                // 处理客户ID格式的请求
                user = userService.getUserByCustomerId(userId);
            } else {
                // 处理数字ID格式的请求
                try {
                    Long id = Long.parseLong(userId);
                    user = userService.getUserById(id);
                } catch (NumberFormatException e) {
                    log.error("【用户服务】用户ID格式错误: {}", userId);
                    return Result.failed("用户ID格式错误");
                }
            }
            
            UserResponse response = convertToUserResponse(user);
            log.info("【用户服务】用户信息查询成功，用户名: {}", response.getUsername());
            return Result.success(response);
        } catch (EntityNotFoundException e) {
            log.error("【用户服务】用户不存在: {}", userId);
            return Result.failed("用户不存在");
        } catch (Exception e) {
            log.error("【用户服务】查询用户信息异常", e);
            return Result.failed("查询用户信息失败");
        }
    }
    
    @GetMapping("/customer/{customerId}")
    public Result<UserResponse> getUserByCustomerId(@PathVariable String customerId) {
        log.info("【用户服务】接收到查询客户请求，客户ID: {}", customerId);
        try {
            User user = userService.getUserByCustomerId(customerId);
            UserResponse response = convertToUserResponse(user);
            log.info("【用户服务】客户信息查询成功，用户名: {}", response.getUsername());
            return Result.success(response);
        } catch (EntityNotFoundException e) {
            log.error("【用户服务】客户不存在: {}", customerId);
            return Result.failed("客户不存在");
        } catch (Exception e) {
            log.error("【用户服务】查询客户信息异常", e);
            return Result.failed("查询客户信息失败");
        }
    }
    
    @GetMapping("/profile/{userId}")
    public Result<Map<String, Object>> getUserProfile(@PathVariable String userId) {
        log.info("【用户服务】接收到查询用户详细资料请求，用户ID: {}", userId);
        try {
            User user;
            // 判断是否是数字ID或客户ID格式
            if (userId.startsWith("CUS")) {
                // 处理客户ID格式的请求
                user = userService.getUserByCustomerId(userId);
            } else {
                // 处理数字ID格式的请求
                try {
                    Long id = Long.parseLong(userId);
                    user = userService.getUserById(id);
                } catch (NumberFormatException e) {
                    log.error("【用户服务】用户ID格式错误: {}", userId);
                    return Result.failed("用户ID格式错误");
                }
            }
            
            // 构建用户详细资料
            Map<String, Object> profile = new HashMap<>();
            profile.put("userId", user.getId().toString());
            profile.put("customerId", user.getCustomerId());
            profile.put("username", user.getUsername());
            profile.put("email", user.getEmail());
            profile.put("phone", user.getPhone());
            profile.put("createdTime", user.getCreatedTime());
            
            // 这里可以添加更多用户相关数据，如收货地址、会员等级等
            
            log.info("【用户服务】用户详细资料查询成功，用户ID: {}", userId);
            return Result.success(profile);
        } catch (EntityNotFoundException e) {
            log.error("【用户服务】用户不存在: {}", userId);
            return Result.failed("用户不存在");
        } catch (Exception e) {
            log.error("【用户服务】查询用户资料异常", e);
            return Result.failed("查询用户资料失败");
        }
    }
    
    // 查询所有商家
    @GetMapping("/merchants")
    public Result<List<UserResponse>> getAllMerchants() {
        log.info("【用户服务】接收到查询所有商家请求");
        try {
            List<User> merchants = userService.getAllMerchants();
            List<UserResponse> responses = merchants.stream()
                    .map(this::convertToMerchantResponse)
                    .collect(Collectors.toList());
            log.info("【用户服务】查询商家成功，总数: {}", responses.size());
            return Result.success(responses);
        } catch (Exception e) {
            log.error("【用户服务】查询商家失败", e);
            return Result.failed("查询商家失败: " + e.getMessage());
        }
    }
    
    // 根据商家ID查询商家
    @GetMapping("/merchant/{merchantId}")
    public Result<UserResponse> getMerchantById(@PathVariable String merchantId) {
        log.info("【用户服务】接收到查询商家请求，商家ID: {}", merchantId);
        try {
            User merchant = userService.getUserByMerchantId(merchantId);
            if (!Boolean.TRUE.equals(merchant.getIsMerchant())) {
                log.warn("【用户服务】用户不是商家，ID: {}", merchantId);
                return Result.failed("该用户不是商家");
            }
            UserResponse response = convertToMerchantResponse(merchant);
            log.info("【用户服务】查询商家成功，商家名: {}", response.getUsername());
            return Result.success(response);
        } catch (EntityNotFoundException e) {
            log.error("【用户服务】商家不存在: {}", merchantId);
            return Result.failed("商家不存在");
        } catch (Exception e) {
            log.error("【用户服务】查询商家失败", e);
            return Result.failed("查询商家失败: " + e.getMessage());
        }
    }
    
    // 将User实体转换为UserResponse DTO，避免返回敏感信息如密码
    private UserResponse convertToUserResponse(User user) {
        UserResponse response = new UserResponse();
        response.setId(user.getId());
        response.setCustomerId(user.getCustomerId());
        response.setUsername(user.getUsername());
        response.setEmail(user.getEmail());
        response.setPhone(user.getPhone());
        response.setEnabled(user.getEnabled());
        response.setCreatedTime(user.getCreatedTime());
        response.setUpdatedTime(user.getUpdatedTime());
        response.setIsMerchant(user.getIsMerchant());
        
        // 如果是商家，添加商家信息
        if (Boolean.TRUE.equals(user.getIsMerchant())) {
            response.setMerchantId(user.getMerchantId());
            response.setMerchantInfo(user.getMerchantInfo());
        }
        
        return response;
    }
    
    // 针对商家的响应转换，可以包含更多商家特有的字段
    private UserResponse convertToMerchantResponse(User merchant) {
        UserResponse response = convertToUserResponse(merchant);
        // 这里可以添加更多商家特有的信息
        return response;
    }
} 